/**
 * PPH平均值重算API路由
 */

const express = require('express');
const router = express.Router();

// 导入PPH计算模块
const {
  oneClickRecalculate,
  calculatePPHAverageForRange,
  updatePPHAverageIncrementally
} = require('../../scheduler/pph-calculator.cjs');

// 导入定时任务管理器
const { pphScheduler } = require('../../scheduler/pph-scheduler.cjs');

// PPH重算进度跟踪
let pphRecomputeProgress = {
  isRunning: false,
  current: 0,
  total: 0,
  percentage: 0,
  startTime: null,
  status: 'idle', // idle, running, completed, error
  error: null,
  jobId: null
};

/**
 * POST /api/pph/recompute
 * PPH平均值重算（异步执行，支持进度跟踪）
 */
router.post('/recompute', async (req, res) => {
  try {
    // 检查并清理僵尸任务
    checkAndCleanZombieTask();

    // 检查是否已有任务在运行
    if (pphRecomputeProgress.isRunning) {
      return res.status(409).json({
        success: false,
        error: '已有PPH重算任务正在运行，请等待完成后再试',
        progress: pphRecomputeProgress
      });
    }

    console.log('📊 收到PPH重算请求:', req.body);

    const { startDate, endDate, fullRange = false, days = 30 } = req.body;
    const jobId = `pph-recompute-${Date.now()}`;

    // 初始化进度跟踪
    pphRecomputeProgress = {
      isRunning: true,
      current: 0,
      total: 0,
      percentage: 0,
      startTime: Date.now(),
      status: 'running',
      error: null,
      jobId: jobId
    };

    // 立即返回任务启动成功
    res.json({
      success: true,
      message: 'PPH重算任务已启动',
      jobId: jobId,
      status: 'running'
    });

    // 异步执行重算任务
    setImmediate(async () => {
      try {
        let result;

        if (fullRange) {
          // 全量重算
          console.log('🔄 执行全量PPH重算...');
          result = await oneClickRecalculate({
            fullRange: true,
            progressCallback: updateProgress
          });
        } else if (startDate && endDate) {
          // 指定日期范围重算
          console.log(`🔄 执行范围PPH重算: ${startDate} 至 ${endDate}`);
          result = await calculatePPHAverageForRange(startDate, endDate, updateProgress);
        } else {
          // 默认天数重算
          console.log(`🔄 执行增量PPH重算: ${days}天`);
          result = await oneClickRecalculate({
            days,
            progressCallback: updateProgress
          });
        }

        console.log('✅ PPH重算完成:', result);

        // 更新完成状态
        pphRecomputeProgress.status = 'completed';
        pphRecomputeProgress.isRunning = false;
        pphRecomputeProgress.percentage = 100;
        pphRecomputeProgress.result = result;

      } catch (error) {
        console.error('❌ PPH重算失败:', error);

        // 更新错误状态
        pphRecomputeProgress.status = 'error';
        pphRecomputeProgress.isRunning = false;
        pphRecomputeProgress.error = error.message || 'PPH重算失败';
      }
    });

  } catch (error) {
    console.error('❌ PPH重算启动失败:', error);

    // 重置进度状态
    pphRecomputeProgress.isRunning = false;
    pphRecomputeProgress.status = 'error';
    pphRecomputeProgress.error = error.message;

    res.status(500).json({
      success: false,
      message: error.message || 'PPH重算启动失败',
      error: error.toString()
    });
  }
});

// 进度更新回调函数
function updateProgress(current, total) {
  pphRecomputeProgress.current = current;
  pphRecomputeProgress.total = total;
  pphRecomputeProgress.percentage = total > 0 ? Math.round((current / total) * 100) : 0;

  if (current % 100 === 0 || current === total) {
    console.log(`📊 PPH重算进度: ${current}/${total} (${pphRecomputeProgress.percentage}%)`);
  }
}

/**
 * 检查并清理僵尸任务
 * 如果任务运行超过4小时，自动标记为失败并清理
 */
function checkAndCleanZombieTask() {
  if (!pphRecomputeProgress.isRunning || !pphRecomputeProgress.startTime) {
    return;
  }

  const now = Date.now();
  const runningTime = now - pphRecomputeProgress.startTime;
  const maxRunningTime = 4 * 60 * 60 * 1000; // 4小时

  if (runningTime > maxRunningTime) {
    console.warn(`🧟 检测到僵尸PPH重算任务，运行时间: ${Math.round(runningTime / 1000 / 60)}分钟，自动清理`);

    // 清理僵尸任务
    pphRecomputeProgress = {
      isRunning: false,
      current: 0,
      total: 0,
      percentage: 0,
      startTime: null,
      status: 'error',
      error: '任务运行超时，已自动清理',
      jobId: null
    };
  }
}

/**
 * GET /api/pph/recompute/progress
 * 获取PPH重算进度
 */
router.get('/recompute/progress', (req, res) => {
  // 每次获取进度时检查僵尸任务
  checkAndCleanZombieTask();

  const progress = {
    ...pphRecomputeProgress,
    percentage: pphRecomputeProgress.total > 0 ?
      Math.round((pphRecomputeProgress.current / pphRecomputeProgress.total) * 100) : 0
  };

  // 计算预估剩余时间
  if (progress.isRunning && progress.current > 0 && progress.startTime) {
    const elapsed = Date.now() - progress.startTime;
    const avgTimePerRecord = elapsed / progress.current;
    const remaining = progress.total - progress.current;
    progress.estimatedTimeRemaining = Math.round((remaining * avgTimePerRecord) / 1000); // 秒
  }

  res.json(progress);
});

/**
 * POST /api/pph/recompute/cleanup
 * 手动清理PPH重算任务状态
 */
router.post('/recompute/cleanup', (req, res) => {
  try {
    console.log('🧹 手动清理PPH重算任务状态');

    // 强制清理任务状态
    pphRecomputeProgress = {
      isRunning: false,
      current: 0,
      total: 0,
      percentage: 0,
      startTime: null,
      status: 'idle',
      error: null,
      jobId: null
    };

    res.json({
      success: true,
      message: 'PPH重算任务状态已清理'
    });

  } catch (error) {
    console.error('❌ 清理PPH重算任务状态失败:', error);

    res.status(500).json({
      success: false,
      message: error.message || '清理失败',
      error: error.toString()
    });
  }
});

/**
 * GET /api/pph/scheduler/status
 * 获取PPH定时任务状态
 */
router.get('/scheduler/status', async (req, res) => {
  try {
    const status = pphScheduler.getStatus();

    res.json({
      success: true,
      ...status
    });

  } catch (error) {
    console.error('❌ 获取PPH定时任务状态失败:', error);

    res.status(500).json({
      success: false,
      message: error.message || '获取状态失败',
      error: error.toString()
    });
  }
});

/**
 * POST /api/pph/scheduler/manual
 * 手动触发PPH定时更新
 */
router.post('/scheduler/manual', async (req, res) => {
  try {
    const { range = 7, force = false } = req.body;
    
    console.log(`🔧 手动触发PPH定时更新: 范围${range}天`);
    
    const result = await pphScheduler.manualUpdate({ range, force });
    
    res.json({
      success: true,
      message: 'PPH手动更新完成',
      ...result
    });
    
  } catch (error) {
    console.error('❌ PPH手动更新失败:', error);
    
    res.status(500).json({
      success: false,
      message: error.message || 'PPH手动更新失败',
      error: error.toString()
    });
  }
});

/**
 * POST /api/pph/scheduler/config
 * 配置PPH定时任务
 */
router.post('/scheduler/config', async (req, res) => {
  try {
    const { updateRange } = req.body;
    
    if (updateRange && updateRange > 0) {
      pphScheduler.setUpdateRange(updateRange);
    }
    
    res.json({
      success: true,
      message: 'PPH定时任务配置已更新',
      status: pphScheduler.getStatus()
    });
    
  } catch (error) {
    console.error('❌ 配置PPH定时任务失败:', error);
    
    res.status(500).json({
      success: false,
      message: error.message || '配置失败',
      error: error.toString()
    });
  }
});

module.exports = router;
